const Koa = require('koa');
const Router = require('koa-router');
const static = require('./routers/static');
const body = require('koa-better-body');
const path = require('path');
const session = require('koa-session');
const fs = require('fs')
const ejs = require('koa-ejs');
const config = require('./config')

let server = new Koa();
server.listen(config.PORT);
console.log(`监听端口${config.PORT}`);

//中间件
server.use(body({
  uploadDir: path.resolve(__dirname, './static/upload')
}));


server.keys = fs.readFileSync('.keys').toString().split('\n');
server.use(session({
  maxAge: 20 * 60 * 1000,
  renew: true
}, server));


//数据库
server.context.db = require('./libs/database');

server.context.config = config;

//渲染
ejs(server, {
  root: path.resolve(__dirname, 'template'),
  layout: false,
  viewExt: 'ejs',
  cache: false,
  debug: false
})


//路由
let router = new Router();
//统一处理 （出错）
// router.use(async (ctx, next) => {
//   try {
//     await next()
//   } catch (error) {
//     ctx.throw(500, 'Internal Server Error')
//   }
// })


router.use('/admin', require('./routers/admin'))
router.use('/api', require('./routers/api'))
router.use('/', require('./routers/www'))

//static 缓存时间设置
static(router, {
  html: 365
})

server.use(router.routes())